package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.StringHttpRequestCallback;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.BookDetailActivity;
import me.shurufa.activities.NewMainActivity;
import me.shurufa.adapter.SearchBookAdapter;
import me.shurufa.bean.DBSearch;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.BookResp;
import me.shurufa.response.DBSearchResp;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.simpledialog.SimpleDialog;
import okhttp3.Headers;
import okhttp3.Response;

/**
 * 搜索
 */
public class SearchBookFragment extends BaseFragment {

    private static final int PAGE_REQUEST_COUNT = 8;

    @Bind(R.id.find_book_number)
    TextView findBookNumber;

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.progress)
    SpinKitView progress;

    private boolean showProgress;
    private int mSearchType;
    private int mWhereFrom;
    private String mSearchKey;
    private String mIsbn;
    private List<DBSearch.BooksEntity> mDataList;
    private SearchBookAdapter mSearchAdapter;

    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter;
    private int mPage = 1;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(mPage);
        }
    };

    public static SearchBookFragment newInstance(int type, int fromWhere) {
        SearchBookFragment fragment = new SearchBookFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.EXTRA_SEARCH_TYPE, type);
        args.putInt(Constants.ARG_FROM_WHERE, fromWhere);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSearchType = getArguments().getInt(Constants.EXTRA_SEARCH_TYPE);
            mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_list_support_empty, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        // 初始化刷新
        findBookNumber.setVisibility(View.GONE);
        mDataList = new ArrayList<>();
        mSearchAdapter = new SearchBookAdapter(getActivity(), mDataList, mSearchType);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mSearchAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setOnScrollListener(mOnScrollListener);

        //onRefresh();
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if(state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    /**
     * 查询
     * @param keyword 关键词
     * @param fromWhere 从哪里来
     */
    public void search(String keyword, int fromWhere) {
        showProgress = true;
        mSearchKey = keyword;
        mSearchType = fromWhere;
        onRefresh();
    }

    /**
     * 通过ISBN查询
     * @param isbn
     */
    public void searchByIsbn(String isbn) {
        showProgress = true;
        mIsbn = isbn;
        onRefresh();
    }

    public void onRefresh() {
        if (TextUtils.isEmpty(mIsbn)) {
            mPage = 1;
            loadData(1);
        } else {
            loadBookByIsbn();
        }
    }

    /**
     * 通过ISBN进行搜索
     */
    private void loadBookByIsbn() {
        HttpRequest.get(String.format(API.SEARCH_BOOK_BY_ISBN_DOUBAN, mIsbn), new StringHttpRequestCallback() {
            @Override
            public void onResponse(Response httpResponse, String response, Headers headers) {
                super.onResponse(httpResponse, response, headers);
                try {
                    DBSearch.BooksEntity book = new Gson().fromJson(response, DBSearch.BooksEntity.class);
                    findBookNumber.setVisibility(View.GONE);
                    // 3. 添加进列表并刷新
                    mSearchAdapter.clear();
                    mSearchAdapter.notifyDataSetChanged();
                    mSearchAdapter.append(book);
                    mSearchAdapter.notifyDataSetChanged();
                    // 异步提交JSON
                    asyncSubmitToServer(response);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    Utils.showToast(R.string.sys_err);
                }
            }

            @Override
            public void onStart() {
                super.onStart();
                if (showProgress) {
                    progress.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                if (showProgress) {
                    progress.setVisibility(View.GONE);
                    showProgress = false;
                }
                Utils.showToast(R.string.sys_err);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (showProgress) {
                    progress.setVisibility(View.GONE);
                    showProgress = false;
                }
            }
        });
    }


    /**
     * 加载数据
     * @param page
     */
    private void loadData(final int page) {
        HttpRequest.get(String.format(API.SEARCH_BOOK_BY_DOUBAN, mSearchKey, PAGE_REQUEST_COUNT, (mPage - 1) * 5), new StringHttpRequestCallback() {
            @Override
            public void onResponse(Response httpResponse, String response, Headers headers) {
                super.onResponse(httpResponse, response, headers);
                try {
                    DBSearch dbSearch = new Gson().fromJson(response, DBSearch.class);
                    if (isAdded()) {
                        findBookNumber.setText(String.format(getString(R.string.found_book), dbSearch.total));
                    }
                    findBookNumber.setVisibility(View.VISIBLE);
                    handleResponse(dbSearch.books, page == 1);
                    // 异步提交JSON
                    asyncSubmitToServer(response);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    Utils.showToast(R.string.sys_err);
                }
            }

            @Override
            public void onStart() {
                super.onStart();
                if (showProgress) {
                    progress.setVisibility(View.VISIBLE);
                    showProgress = false;
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                super.onFailure(errorCode, msg);
                progress.setVisibility(View.GONE);
                Utils.showToast(R.string.sys_err);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                progress.setVisibility(View.GONE);
                refreshComplete();
            }
        });
    }

    /**
     * 异步提交搜索数据
     * @param json
     */
    private void asyncSubmitToServer(String json) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("book_data", json);
        HttpRequest.post(API.ASYNC_SUBMIT_JSON_TO_SERVER, params, new HttpCallback<DBSearchResp>() {

            @Override
            public void onRespSuccess(DBSearchResp dbSearchResp) {
            }

            @Override
            public void onRespFailure(DBSearchResp dbSearchResp) {

            }
        });
    }

    /**
     * 处理返回结果
     * @param books     data
     * @param isPullToRefresh  boolean
     */
    private void handleResponse(List<DBSearch.BooksEntity> books, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = !Utils.isNullForList(books);


        // 2. 去重
        if (isPullToRefresh) {
            mSearchAdapter.clear();
            mSearchAdapter.notifyDataSetChanged();
        }

        // 3. 添加进列表并刷新
        mSearchAdapter.append(books);

        // 4. 页码自增
        mPage ++;

    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.EVENT_CLICK_SEARCHBOOK_ITEM_DOUBAN.equals(intent.getAction())) {
            String isbn = intent.getStringExtra(Constants.EXTRA_SEARCH_ISBN);
            reqBookByIsbn(isbn);
            return;
        }

        if (Constants.EVENT_CLICK_SEARCHBOOK_ITEM_DOUBAN_ADD_TO_SHELF.equals(intent.getAction())) {
            String isbn = intent.getStringExtra(Constants.EXTRA_SEARCH_ISBN);
            reqBookByIsbnAddShelf(isbn);
        }
    }

    /**
     * 显示添加到我的书架Dialog
     * @param book_id
     */
    private void showAddToShelfDlg(final String book_id) {
        SimpleDialog dialog = new SimpleDialog(getActivity());
        if (isAdded()) {
            dialog.setContentText(getString(R.string.positive_to_add));
        }
        dialog.setAnimationEnable(true);
        dialog.setOnNegativeListener("取消", new SimpleDialog.OnNegativeListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
            }
        });
        dialog.setOnPositiveListener("确定", new SimpleDialog.OnPositiveListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
                reqAddBookToShlef(book_id);
            }
        }).show();
    }
    /**
     * 添加到我的书架
     * @param book_id
     */
    private void reqAddBookToShlef(final String book_id) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("book_id", book_id);
        HttpRequest.post(API.ADD_BOOK_TO_SHELF, params, new HttpCallback<BaseResp>() {
            @Override
            public void onRespSuccess(BaseResp resp) {

                try {
                    // 从添加书摘里的 添加书摘本进来
                    if (mWhereFrom == Constants.TYPE_FROM_ADD_DIGEST_ADD_NOTEBOOK) {
                        Intent in = new Intent(Constants.EVENT_ADD_NOTEBOOK_FROM_ADD_DIGEST);
                        EventBus.getDefault().post(in);
                        getActivity().finish();
                    } else {
                        EventBus.getDefault().post(Constants.EVENT_SWITCH_MY_SHELF);
                        getActivity().finish();

                        Intent in = new Intent(getActivity(), NewMainActivity.class);
                        in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        getActivity().startActivity(in);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }

        });
    }

    /**
     * 根据ISBN获取Book 跳进书详情界面
     * @param isbn isbn
     */
    private void reqBookByIsbn(String isbn) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("isbn", isbn);
        HttpRequest.post(API.GET_BOOK_BY_ISBN, params, new HttpCallback<BookResp>(getActivity()) {

            @Override
            public void onRespSuccess(BookResp resp) {
                try {
                    Intent in = new Intent(getActivity(), BookDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mSearchType);
                    in.putExtra(Constants.ARG_BOOK, resp.data);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    in.putExtra(Constants.ARG_FROM_WHERE, Constants.TYPE_FRAGMENT_NEWEST_BOOK);
                    getActivity().startActivity(in);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BookResp resp) {

            }
        });
    }

    /**
     * 根据ISBN获取Book 并且添加到我的书摘本
     * @param isbn isbn
     */
    private void reqBookByIsbnAddShelf(String isbn) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("isbn", isbn);
        HttpRequest.post(API.GET_BOOK_BY_ISBN, params, new HttpCallback<BookResp>(getActivity()) {

            @Override
            public void onRespSuccess(BookResp resp) {
                try {
                    showAddToShelfDlg(String.valueOf(resp.data.id));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BookResp resp) {

            }
        });
    }
}
